using System;
using System.Data;
using Gtk;
using Npgsql;
using Serpis;

public partial class MainWindow : Gtk.Window
{
	private IDbConnection conexion;
	private IDbCommand command;
	private IDataReader dataReader;
	
	public MainWindow () : base(Gtk.WindowType.Toplevel)
	{
		Build ();
		
		conexion = AppDbConnection.Instance.DbConnection;
		
		actualizar();
		newAction.Activated += delegate 
		{
			insertar();
			actualizar();
		};	
	}
	
	private void insertar()
	{
		command = conexion.CreateCommand();
		command.CommandText = "INSERT INTO articulo (id, nombre, precio, categoria) values ('8', 'new', '12', '2')";
		command.ExecuteNonQuery();
	}
	
	private void actualizar()
	{
		//**	Limpiamos columnas
		foreach (TreeViewColumn treeViewColumn in treeview.Columns)
		{
			treeview.RemoveColumn(treeViewColumn);
		}
		
		command = conexion.CreateCommand();conexion = AppDbConnection.Instance.DbConnection;
		command.CommandText = "SELECT * FROM articulo;";
		dataReader = command.ExecuteReader();
		
		for(int i=0; i<dataReader.FieldCount; i++)
		{
			treeview.AppendColumn(dataReader.GetName(i), new CellRendererText(), "text", i);
		}
		
		Type[] types = new Type[dataReader.FieldCount];
		for(int i=0; i<types.Length; i++)
		{command.CommandText = "SELECT * FROM articulo;";
			types[i]=typeof(string);
		}

		ListStore listStore = new ListStore(types);
		treeview.Model = listStore;
		
		object[] values = new object[dataReader.FieldCount];
		string[] strings = new string[values.Length];
		
		while(dataReader.Read())
		{
			dataReader.GetValues(values);
			for(int i=0;i<values.Length; i++)
			{
				if(dataReader.IsDBNull(i))
				{
					strings[i] = "null";
				}
				else
				{
					strings[i] = values[i].ToString();
				}
			}
			listStore.AppendValues(strings);
		}
		dataReader.Close();	
	}
	
	
	protected void OnDeleteEvent (object sender, DeleteEventArgs a)
	{
		Application.Quit ();
		a.RetVal = true;
	}
}
